package com.thzy.bbs.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.iid.FirebaseInstanceId;
import com.thzy.bbs.R;
import com.thzy.bbs.common.ActivityConfig;
import com.thzy.bbs.common.CommonUtils;
import com.thzy.bbs.common.Constants;
import com.thzy.bbs.common.StringUtils;
import com.thzy.bbs.dao.UserDao;
import com.thzy.bbs.entity.User;
import com.thzy.bbs.thread.LoginThread;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Date;


/**
 * 启动页设置
 *
 * @author lirui
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends AppCompatActivity {
    @ViewInject(R.id.user_name)
    private TextView userNameText;
    @ViewInject(R.id.pass_word)
    private TextView passWordText;
    @ViewInject(R.id.login_button)
    private Button loginButton;
    private UserDao userDao = new UserDao();
    //用户上次登录数据
    private User user;
    /**
     * 设备标识号
     * 未注册为null
     */
    public static String TOKEN = FirebaseInstanceId.getInstance().getToken();

    /**
     * 消息线程处理
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject jsonObject;
            String text;
            try {
                jsonObject = new JSONObject(msg.obj.toString());
                text = jsonObject.getString("msg");
                Boolean success = jsonObject.getBoolean("success");
                CommonUtils.session = jsonObject.getString("data");
                if (success) {
                    successNext();
                    return;
                }
                isToggle(true);
            } catch (JSONException ignored) {
                text = LoginActivity.this.getString(R.string.login_error);
                isToggle(true);
            }
            Toast.makeText(LoginActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 登陆成功存储数据库，跳转
     */
    private void successNext() {
        String userName = userNameText.getText().toString();
        Date lastTime = new Date(System.currentTimeMillis());
        if (user == null) {
            user = new User(userName, lastTime);
        } else {
            user.setUserName(userName);
            user.setLastTime(lastTime);
        }
        userDao.saveOrUpdate(user);
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        LoginActivity.this.startActivity(intent);
        LoginActivity.this.finish();
    }

    /**
     * 构造函数
     */
    public LoginActivity() {
        this.user = userDao.findFirstByCreateTimeDesc();
    }

    /**
     * 创建
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        x.view().inject(this);
        //判断是否是挤下线
        Intent intent = getIntent();
        boolean isOffline = intent.getBooleanExtra(ActivityConfig.parameterName.OFFLINE, false);
        if (isOffline) {
            Toast.makeText(LoginActivity.this, R.string.other_loge, Toast.LENGTH_SHORT).show();
        }
        //存在记录用户账号自动填充
        if (user != null) {
            userNameText.getEditableText().insert(userNameText.getText().length(), user.getUserName());
        }
    }

    /**
     * 是否打开输入
     *
     * @param isOpen
     */
    private void isToggle(Boolean isOpen) {
        userNameText.setEnabled(isOpen);
        passWordText.setEnabled(isOpen);
        loginButton.setClickable(isOpen);
    }

    /**
     * 点击按钮事件
     *
     * @param v 点击控件
     * @author Lirui
     */
    @Event(value = {R.id.login_button, R.id.login_background}, type = View.OnClickListener.class)
    private void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.login_button:
                String userName = userNameText.getText().toString();
                String passWord = passWordText.getText().toString();
                if (!verification(userName, passWord)) {
                    return;
                }
                isToggle(false);
                Toast.makeText(LoginActivity.this, this.getString(R.string.LOADING), Toast.LENGTH_SHORT).show();
                //设备id为空给123456默认值
                new Thread(new LoginThread(userName, passWord, handler, StringUtils.isBlank(TOKEN) ? Constants.EquipmentInfo.DEFAULT_TOKEN : TOKEN)).start();
                break;
            case R.id.login_background:
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
        }
    }

    /**
     * 为空验证
     *
     * @param userName 用户名
     * @param passWord 密码
     * @return
     */
    private boolean verification(String userName, String passWord) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(passWord)) {
            Toast.makeText(this, this.getString(R.string.empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
